package org.phpgwt.phpgenerator;

import org.phpgwt.Utility;

import com.google.gwt.core.ext.LinkerContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.linker.AbstractLinker;
import com.google.gwt.core.ext.linker.ArtifactSet;
import com.google.gwt.core.ext.linker.LinkerOrder;

/**
 * 
 * Linker to output PHP file
 * 
 * @author baloghf87@gmail.com
 * 
 */
@LinkerOrder(LinkerOrder.Order.POST)
public class PHPLinker extends AbstractLinker {

	@Override
	public String getDescription() {
		return "PHPLinker";
	}

	@Override
	public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException {
		ArtifactSet artifactSet = new ArtifactSet(artifacts);

		try {
			String phpContent = PHPGenerator.generatePHP(context);
			artifactSet.add(emitString(logger, phpContent, "phpgwt.php"));

			for (String className : Utility.getConfigurationProperties(context, "phpgwt_services")) {
				String stubs = PHPStubsGenerator.generate(className);

				if (stubs != null) {
					artifactSet.add(emitString(logger, stubs, String.format("stubs/%s.php", Utility.getShortClassName(className))));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new UnableToCompleteException();
		}

		return artifactSet;
	}
}